import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Material, MaterialDocument } from '../schemas/materials/material.schema';
import * as fs from 'fs';
import * as path from 'path';

const uploadPath = path.resolve(__dirname, '../../uploads');

@Injectable()
export class MaterialsService {
  constructor(
    @InjectModel(Material.name) private materialModel: Model<MaterialDocument>,
  ) {}

  async create(createMaterialDto: { content: string; category: string; imageUrls: string[] }): Promise<Material> {
    const createdMaterial = new this.materialModel(createMaterialDto);
    return createdMaterial.save();
  }

  async findOne(id: string): Promise<Material> {
    const material = await this.materialModel.findById(id).exec();
    if (!material) throw new NotFoundException('材料不存在');
    return material;
  }

  async findAll() {
    return this.materialModel.find().exec();
  }

  async update(id: string, updateData: any, files?: Express.Multer.File[]) {
    const material = await this.materialModel.findById(id);
    if (!material) throw new NotFoundException('材料不存在');

    // 更新图片
    if (files?.length) {
      material.imageUrls.forEach(imageUrl => {
        const filename = path.basename(imageUrl);
        const filePath = path.join(uploadPath, filename);
        if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
      });
      material.imageUrls = files.map(file => `/uploads/${file.filename}`);
    }

    Object.assign(material, updateData);
    return material.save();
  }

  async remove(id: string): Promise<{ deleted: boolean }> {
    const material = await this.materialModel.findByIdAndDelete(id);
    if (!material) throw new NotFoundException('材料不存在');

    // 删除关联图片
    material.imageUrls.forEach(imageUrl => {
      const filePath = path.join(uploadPath, path.basename(imageUrl));
      if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
    });

    return { deleted: true };
  }
}